#include <string.h>
#include <iostream>
using std::cout;
using std::endl;


class Computer
{
public:
    Computer(const char * brand,double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        _totalPrice += _price;
        cout << "Computer(const char *,double)" << endl;
        strcpy(_brand,brand);
    }
 
    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {
        _totalPrice += _price;
        strcpy(_brand,rhs._brand);//进行深拷贝
        cout << "Computer(const Computer &)" << endl;
    }

    Computer & operator=(const Computer & rhs){
        cout << "赋值运算符函数" << endl;
        if(this != &rhs){//1.考虑自复制情况
            _totalPrice -= _price;
            delete [] _brand; //2.回收本对象的数据成员原本管理的堆空间
            _brand = new char[strlen(rhs._brand) + 1]();//3.深拷贝
            strcpy(_brand,rhs._brand);
            _price = rhs._price;//对其他的数据成员完成赋值
            _totalPrice += _price;
        }
        return *this;//4.返回本对象
    }


    void print() 
    {
        cout << "brand:" << _brand << endl;
        cout << "price:" << _price << endl;
    }

    static void printTotalPrice(){
        cout << "totalPrice:" << _totalPrice << endl;
    }

    ~Computer(){
        cout << "~Computer()" << endl;
        if(_brand){
            _totalPrice -= _price;
            delete [] _brand;
            _brand = nullptr;//安全回收
        }
    }
private:
    char * _brand;
    double _price;
    static double _totalPrice;
};
double Computer::_totalPrice = 0;


void test0(){
    Computer pc("huawei",7000);
    Computer pc2("apple",20000);
    Computer pc3("lenovo",8000);
    Computer pc4 = pc2;
    pc3 = pc2;
    /* pc.print(); */
    /* pc.printTotalPrice(); */

    Computer::printTotalPrice();

    cout << endl;
    cout << sizeof(Computer) << endl;

    /* pc._totalPrice; */
    /* Computer::_totalPrice = 1; */


 }

int main(void){
    test0();
    /* cout << _totalPrice << endl; */
    return 0;
}
